package aaa.screen;

import java.text.SimpleDateFormat;
import java.util.Date;

import aaa.database.Database;
import aaa.exception.AAAException;
import aaa.schedule.Schedule;
import aaa.schedule.ScheduleConstants;
import aaa.schedule.parameters.ScheduleName;
import aaa.schedule.parameters.SchedulePeriod;
import aaa.schedule.parameters.ScheduleProjectId;
import aaa.update.UpdateManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

/**
 * View displaying the form for editing a schedule.
 * 
 * @author		Schnell Michaël, Zanette Sébastien
 */
public class EditScheduleScreen extends CreateScheduleScreen implements ScheduleConstants {

	/**
	 * Original values for the edited schedule.
	 */
	protected Schedule originalS ;

	/**
	 * Initializes this view.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, "Edition d'un emploi du temps");
	}// onCreate(Bundle)

	/**
	 * Initializes the fields list with the values from the edited schedule.
	 */
	@Override
	public void init() {
		Database db = new Database(this) ;
		Bundle b = this.getIntent().getExtras() ;
		String name = b.getString("aaa.screen.nameCurrentSchedule") ;
		try {
			this.originalS = db.getScheduleWithName(name) ;
		} catch (AAAException e) {
			// The edited schedule doesn't exit, 
			// go back to the previous page
			this.onBackPressed() ;
		}// try

		this.init(this.originalS.getName(), 
				this.originalS.getRessources(), 
				Integer.toString(this.originalS.getPeriod()), 
				Integer.toString(this.originalS.getProjectId())) ;
	}// init()

	/**
	 * Returns an instance of an {@code OnClickListener} for the save action.
	 * 
	 * @return	instance of an {@code OnClickListener} for the save action
	 */
	@Override
	protected OnClickListener getSaveListener() {
		return new SaveListener(this) ;
	}// getSaveListener()

	/**
	 * OnClickListener for the save button.
	 * 
	 * <p>Retrives the data from the form and updates the schedule in the database
	 * if possible.
	 * 
	 * @author 	Schnell Michaël
	 */
	class SaveListener implements OnClickListener {

		/**
		 * View containing the component attached to this listener.
		 */
		protected EditScheduleScreen container ;

		/**
		 * Sole constructor. 
		 * 
		 * @param 	container
		 * 			View containing the component attached to this listener
		 */
		public SaveListener(EditScheduleScreen container) {
			super();
			this.container = container;
		}// SaveListener(EditScheduleScreen)

		/**
		 * Handles the click on the attached component.
		 * 
		 * @param	actualView
		 * 			view of the component who has received a click event
		 */
		public void onClick(View actualView) {
			// Retrieve form data
			String name       = this.container.getById(ScheduleName.FIELD_ID).getValue(this.container.getFields()).toString() ;
			String ressources = this.container.getScheduleResources() ;
			int period        = (Integer) this.container.getById(SchedulePeriod.FIELD_ID).getValue(this.container.getFields()) ;
			int projectId     = (Integer) this.container.getById(ScheduleProjectId.FIELD_ID).getValue(this.container.getFields()) ;
			String lastModif  = "null" ;
			int notify        = 1 ;
			String created    = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date()) ;

			// Data testing and schedule update
			Schedule newS = new Schedule(projectId, name, ressources, period, lastModif, notify, created) ;
			try {
				Schedule original = this.container.getOriginalSchedule() ;
				// The user has made changes
				if (!original.equals(newS)) {
					Database db = new Database(this.container) ;
					if (original.getName().equals(newS.getName())) {
						newS.validateOnUpdate() ;
					} else {
						newS.validate(db) ;
					}// if
					// Update the changes in the database
					db.updateSchedule(original.getName(), newS) ;
					// Retrieve the new lessons
					if (!original.getRessources().equals(newS.getRessources())
							|| (original.getProjectId() != newS.getProjectId())
							|| (original.getPeriod() != newS.getPeriod())) {
						Intent intent = new Intent(this.container, UpdateManager.class) ;
						intent.putExtra("aaa.schedule.name", name) ;
						this.container.startService(intent) ;
						//UpdateManager.getInstance().addQueue(newS.getName()) ;
					}// if
				}// if
				//TODO Issue 3 (-> GC)
				this.container.onBackPressed() ;
			} catch (AAAException e) {
				Toast.makeText(this.container, e.getMessage(), Toast.LENGTH_LONG).show() ;
			}// try
		}// onClick(View)  
		
	}// class SaveListener

	/**
	 * Returns the original values of the edited schedule.
	 * 
	 * @return	instance of {@code Schedule}
	 */
	public Schedule getOriginalSchedule() {
		return this.originalS;
	}// getOriginalSchedule()

	/**
	 * Used to display error messages if a schedule could not be updated.
	 * 
	 * <p>If the edited schedule is being updated, we discard any unsaved changes
	 */
	@Override
	public void onUpdate(Object... args) {
		super.onUpdate(args) ;
		try {
			// If the edited schedule is being updated, we discard the changes
			// made and return to the previous view
			String scheduleName = (String)  args[0] ;
			int scheduleState   = (Integer) args[1] ;
			if (scheduleName.equals(this.originalS.getName()) 
					&& (scheduleState == STATUS_UPDATING)) {
				this.onBackPressed() ;
			}// if
		} catch (Exception e) {}// try
	}// onUpdate(Object...)

}// class EditScheduleScreen